<?php

namespace App\Traits;

use Carbon\CarbonImmutable;
use Illuminate\Support\Carbon;

trait UuidTrait
{
    public static function bootUuidTrait()
    {
        static::creating(function (\Illuminate\Database\Eloquent\Model $model) {

            $model->guarded = [];
            $model->keyType = 'string';
            $model->incrementing = false;

            $model->{$model->getKeyName()} = $model->{$model->getKeyName()} ?: \Str::orderedUuid()->toString();
        });
    }

    public function getIncrementing(): bool
    {
        return false;
    }

    public function getKeyType(): string
    {
        return 'string';
    }

    public function getGuarded(): array
    {
        return [];
    }

    protected function serializeDate(\DateTimeInterface $date)
    {
        return $date instanceof \DateTimeImmutable ?
            CarbonImmutable::instance($date)->toDateTimeString() :
            Carbon::instance($date)->toDateTimeString();
    }
}
